package leetcode_字符串._07数字与字符串间转换;

import java.util.*;

/**
 * 求解方程
 */
public class _640 {
    public static void main(String[] args) {
//        String s = "x+5-3+x=6+x-2";
//        System.out.println(Arrays.toString(s.split("=")));
//        String  s = "+2";
//        System.out.println(Integer.parseInt(s));
        // System.out.println(Arrays.toString(get(new char[]{'x', '+', '5', '-', '3', '+', 'x'})));
        // System.out.println(new _640().solveEquation("-x=-1"));
    }

    public String solveEquation(String equation) {
        String[] expression = equation.split("=");
        int[] left = get(expression[0].toCharArray());
        int[] right = get(expression[1].toCharArray());
        int x = left[0] - right[0], n = right[1] - left[1];
        if (x == 0) {
            if (n == 0) {
                return "Infinite solutions";
            }
            return "No solution";
        }
        int a = 18, b = 12;
        while (b != 0) {
            int c = a % b;
            a = b;
            b = c;
        }
        return "x=" + (n / x);
    }

    public int[] get(char[] ex) {
        int x = 0, n = 0;
        List<String> list = new ArrayList<>();
        StringBuilder tem = new StringBuilder();
        for (int i = 0; i < ex.length; i++) {
            if (ex[i] == '+' || (ex[i] == '-' && i != 0)) {
                list.add(tem.toString());
                tem.delete(0, tem.toString().length());
                if (ex[i] == '+') {
                    continue;
                }
            }
            tem.append(ex[i]);
            if (i == ex.length - 1) {
                list.add(tem.toString());
            }
        }
        for (int i = 0; i < list.size(); i++) {
            String s = list.get(i);
            if (s.contains("x")) {
                String[] xes = s.split("x");
                // x
                if (xes.length == 0) {
                    x += 1;
                    continue;
                }
                // -x
                if (xes[0].equals("-")) {
                    x -= 1;
                    continue;
                }
                // -2x 2x
                x += Integer.parseInt(xes[0]);
                continue;
            }
            n += Integer.parseInt(s);
        }
        return new int[]{x, n};
    }

}
